package com.ca.ridersclubapplication.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.ClubListActivity;
import com.ca.ridersclubapplication.LoginActivity;
import com.ca.ridersclubapplication.MainActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.bean.MiniClubInfo;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.ClubClassify;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.view.FollowMiniClubListCallbackView;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.ClubRequester;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.dto.ClubDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.TestUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.list.FollowMiniClubListView;
import com.ca.ridersclubapplication.view.list.SortListView;

import java.util.ArrayList;
import java.util.List;

public class FoundFragment extends Fragment implements RefreshableFragment {

    private ConstraintLayout parentCL;
    private FollowMiniClubListView followMiniClubListView;
    private SortListView sortClubLV;

    private CallbackView callbackView;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_found_layout, container, false);

        initView(view);

        initListener();

        loadData();

        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initView(View view) {

        parentCL = view.findViewById(R.id.cl_parent);

        //  关注的车友会列表
        followMiniClubListView = view.findViewById(R.id.lv_followClub);
        followMiniClubListView.setActivity(getActivity());

        //  车友会分类排序列表
        sortClubLV = view.findViewById(R.id.lv_sortClub);
        sortClubLV.setActivity(getActivity());

        //  设置距离手机顶部的距离
        parentCL.setPadding(0, MainActivity.getTitleCLHeight() + 8, 0, 0);

        //  因为关注车友会列表需要用户登录，所以需要将其放入数据处理器中
        DataHandler.putView("Login", new FollowMiniClubListCallbackView(followMiniClubListView));

        //  第一次加载主动请求是否登录
        DataHandler.putData(new BooleanEntity("Login", DataHandler.isLogin(getActivity())));

        //  用户登录状态的改变将影响关注列表的展示，因此放入数据处理器中
        callbackView = new CallbackView() {
            @Override
            public void update() {
                Handleable data = DataHandler.getData("Login");
                if (data instanceof BooleanEntity) {
                    boolean isLogin = ((BooleanEntity) data).getValue();
                    if (isLogin) {
                        //  如果用户登录了，则请求关注列表
                        listFollowClub();
                    }
                    else {
                        //  否则关注列表置空
                        followMiniClubListView.setMiniInfoList(new ArrayList<>());
                    }
                }
            }
        };
        DataHandler.putView("Login", callbackView);

        DataHandler.putView("HasNewFollowClub", new CallbackView() {
            @Override
            public void update() {
                listFollowClub();
            }
        });
    }

    private void initListener() {

        followMiniClubListView.gotoLoginButton.setOnClickListener(v -> {
            if (DataHandler.isLogin(getActivity())) {
                Toast.makeText(getActivity(), "已登录", Toast.LENGTH_SHORT).show();
                //  请求数据
                loadData();
            }
            else {
                FragmentActivity activity = getActivity();
                if (activity != null) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("clickIndex", 1);
                    activity.startActivity(intent);
                }
            }
        });

        followMiniClubListView.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ClubListActivity.class);
            intent.putExtra("classify", "follow:" + DataHandler.getToken(getActivity()).getId());
            startActivity(intent);
        });
    }

    private void loadData() {

        //  请求关注的车友会列表
        listFollowClub();

        //  请求车友会分类列表
        listClubClassify();
    }

    private void listFollowClub() {
        if (DataHandler.isLogin(getActivity())) {
            ClubRequester.listFollowClub(getActivity(), DataHandler.getToken(getActivity()).getId(), new AfterExecutor<List<ClubDto>>() {
                @Override
                public void execute(Result<List<ClubDto>> result) {
                    if (result.isSuccess()) {
                        //  请求成功，设置关注列表视图
                        List<ClubDto> data = result.getData();
                        List<MiniClubInfo> list = new ArrayList<>();
                        for (ClubDto dto : data) {
                            list.add(new MiniClubInfo(
                                    dto.getId(),
                                    FileRequester.CLUB_IMAGE_1_1_BASE_URL + dto.getId(),
                                    dto.getName()));
                        }
                        followMiniClubListView.setMiniInfoList(list);
                    }
                }
            });
        }
    }

    private void listClubClassify() {
        ClubRequester.listAllClassify(getActivity(), new AfterExecutor<List<ClubClassify>>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void execute(Result<List<ClubClassify>> result) {
                if (result.isSuccess()) {
                    //  请求成功，设置数据
                    List<ClubClassify> data = result.getData();
                    for (ClubClassify classify : data) {
                        classify.setImageUrl(FileRequester.CLASSIFY_IMAGE_BASE_URL + classify.getId());
                    }
                    sortClubLV.setList(data);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        DataHandler.removeView("Login", callbackView);
    }

    @Override
    public void refresh() {
        //  重新请求数据
        loadData();
        //  关闭下拉刷新动画
        MainActivity activity = (MainActivity) getActivity();
        if (activity != null) {
            activity.stopRefreshing();
        }
    }
}
